package com.fiberhome.boot.demo.rabbitmq.controller;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.json.JSONException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fiberhome.boot.conf.rabbitmq.AmqpConfig;
import com.fiberhome.boot.demo.rabbitmq.dao.PersonDao;
import com.fiberhome.boot.demo.rabbitmq.domain.Person;
import com.fiberhome.boot.utils.ObjectAndByte;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value="/mq")
@Api(value = "rabbitmq消息持久化测试", description="rabbitmq消息持久化测试", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class PersonController {

	@Autowired
	PersonDao dao;
	
	@Autowired
    RabbitTemplate rabbitTemplate;
	
	MessagePostProcessor temp;

	@ApiOperation(value="根据id获取用户", notes="根据id获取用户")
	@RequestMapping(value="person/{id}",method=RequestMethod.GET)
	public Person getPersonById(@PathVariable("id")int id){
		return dao.findById(id);
	}
	
	
	@ApiOperation(value="测试rabbitmq消息队列（消息实体为Person对象）", notes="测试rabbitmq消息队列（消息实体为Person对象")
	@RequestMapping(value="/sendUser",method=RequestMethod.POST)
	public String sendUser(@RequestBody Person person) throws JSONException, IOException, InterruptedException{
		Message message = MessageBuilder.withBody(ObjectAndByte.toByteArray(person)).
				setTimestamp(new Date()).setMessageId("test123").build();
		rabbitTemplate.convertAndSend(AmqpConfig.EXCHANGE, AmqpConfig.ROUTINGKEY, message);
        return "message send success";
	}
	
	
}
